<template>
  <div class="project-detail-container">
    <div v-if="loading" class="loading">
      加载中...
    </div>
    <div v-else-if="!project || project.name === '项目详情页面正在开发中'" class="error">
      项目详情页面正在开发中...
    </div>
    <div v-else class="project-detail">
      <!-- 项目头部进度 -->
      <div class="project-header">
        <h1 class="project-title">{{ project.name }}</h1>
        <div class="project-progress">
          <span class="progress-label">形象进度：</span>
          <div class="progress-bar">
            <div class="progress-fill" :style="{ width: project.progress + '%' }"></div>
          </div>
          <span class="progress-value">{{ project.progress }}%</span>
        </div>
      </div>

      <!-- 项目图片卡片 -->
      <div class="project-image-card">
        <img class="project-image" :src="getImageUrl(project.images ? project.images[0] : null)" alt="项目图片">
        <div class="follow-button" @click="toggleFollow">
          <span>{{ isFollowed ? '已关注' : '关注' }}</span>
        </div>
      </div>

      <!-- 基本信息卡片 -->
      <div class="card">
        <div class="card-header" @click="toggleCollapse('basicInfo')">
          <h2 class="card-title">基本信息</h2>
          <span class="card-arrow" :class="{'is-open': collapseState.basicInfo}">›</span>
        </div>
        <div class="card-content" v-if="collapseState.basicInfo">
          <div class="info-list">
            <div class="info-item">
              <span class="info-label">调度层级</span>
              <span class="info-value">{{project.level || '暂无数据'}}</span>
            </div>
            <div class="info-item">
              <span class="info-label">项目名称</span>
              <span class="info-value">{{project.name}}</span>
            </div>
            <div class="info-item">
              <span class="info-label">投资主体</span>
              <span class="info-value">{{project.investor}}</span>
            </div>
            <div class="info-item">
              <span class="info-label">建设性质</span>
              <span class="info-value">{{project.nature || '暂无数据'}}</span>
            </div>
            <div class="info-item">
              <span class="info-label">项目地址</span>
              <span class="info-value">{{project.address || '巴林右旗'}}</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 投资信息卡片 -->
      <div class="card">
        <div class="card-header" @click="toggleCollapse('investInfo')">
          <h2 class="card-title">投资信息</h2>
          <span class="card-arrow" :class="{'is-open': collapseState.investInfo}">›</span>
        </div>
        <div class="card-content" v-if="collapseState.investInfo">
          <div class="info-list">
            <div class="info-item">
              <span class="info-label">总投资</span>
              <span class="info-value">{{project.totalInvestment || project.investment || '暂无数据'}}万元</span>
            </div>
            <div class="info-item">
              <span class="info-label">2025年计划完成投资</span>
              <span class="info-value">{{project.plannedInvestment2025 || '暂无数据'}}万元</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 时间信息卡片 -->
      <div class="card">
        <div class="card-header" @click="toggleCollapse('timeInfo')">
          <h2 class="card-title">时间信息</h2>
          <span class="card-arrow" :class="{'is-open': collapseState.timeInfo}">›</span>
        </div>
        <div class="card-content" v-if="collapseState.timeInfo">
          <div class="info-list">
            <div class="info-item">
              <span class="info-label">计划开复工时间</span>
              <span class="info-value">{{project.plannedStartDate || '暂无数据'}}</span>
            </div>
            <div class="info-item">
              <span class="info-label">计划完工时间</span>
              <span class="info-value">{{project.plannedEndDate || '暂无数据'}}</span>
            </div>
            <div class="info-item">
              <span class="info-label">建设周期</span>
              <span class="info-value">{{project.period || '暂无数据'}}</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 责任信息卡片 -->
      <div class="card">
        <div class="card-header" @click="toggleCollapse('responsibilityInfo')">
          <h2 class="card-title">责任信息</h2>
          <span class="card-arrow" :class="{'is-open': collapseState.responsibilityInfo}">›</span>
        </div>
        <div class="card-content" v-if="collapseState.responsibilityInfo">
          <div class="info-list">
            <div class="info-item">
              <span class="info-label">分管领导</span>
              <span class="info-value">{{project.supervisor || '暂无数据'}}</span>
            </div>
            <div class="info-item">
              <span class="info-label">责任单位</span>
              <span class="info-value">{{project.responsibleUnit || '暂无数据'}}</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 前期手续办理情况 -->
      <div class="card action-card" @click="openPopup">
        <div class="card-header">
          <h2 class="card-title">前期手续办理情况</h2>
          <span class="card-action">查看</span>
        </div>
      </div>

      <!-- 项目进展情况 -->
      <div class="card action-card" @click="openPopupProgress">
        <div class="card-header">
          <h2 class="card-title">项目进展情况</h2>
          <span class="card-action">查看</span>
        </div>
      </div>

      <!-- 项目图片 -->
      <div class="card">
        <div class="card-header">
          <h2 class="card-title">项目图片</h2>
        </div>
        <div class="card-content">
          <div class="image-gallery">
            <div class="gallery-item" v-for="(image, index) in project.images" :key="index">
              <img :src="getImageUrl(image)" :alt="'项目图片 ' + (index + 1)">
            </div>
          </div>
        </div>
      </div>

      <!-- 审批手续弹窗 -->
      <div class="popup-wrapper" v-if="showPopup">
        <div class="popup-overlay" @click="closePopup"></div>
        <div class="popup-content">
          <div class="popup-header">
            <h3 class="popup-title">审批手续办理情况</h3>
          </div>
          <div class="popup-body">
            <div class="table-content">
              <div class="table-row" v-for="(row, index) in tableData" :key="index">
                <div class="table-cell">
                  <span class="cell-label">{{truncateText(row.header1, 20)}}</span>
                  <div class="cell-value-container">
                    <div class="cell-value" :class="getStatusClass(row.value1)">
                      <span>{{row.value1}}</span>
                    </div>
                    <span v-if="row.value1 === '是'" class="detail-link" @click="goDetail(true, index)">查看详情</span>
                    <span v-if="row.value1 === '否'" class="detail-link" @click="goDetail(false, index)">查看详情</span>
                    <span v-if="row.value1 === '无需办理'" class="detail-link" @click="goDetail(true, index)">查看详情</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class="popup-close" @click="closePopup">
            <span class="close-icon">×</span>
          </div>
        </div>
      </div>

      <!-- 项目进展弹窗 -->
      <div class="popup-wrapper" v-if="showProgressPopup">
        <div class="popup-overlay" @click="closePopupProgress"></div>
        <div class="popup-content">
          <div class="popup-header">
            <h3 class="popup-title">项目进展情况</h3>
          </div>
          <div class="popup-body">
            <div class="progress-content">
              <p class="progress-text">{{project.progressDetails || '暂无项目进展数据'}}</p>
            </div>
          </div>
          <div class="popup-close" @click="closePopupProgress">
            <span class="close-icon">×</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import axios from 'axios'
import config from '@/config.js'

export default {
  setup() {
    const route = useRoute()
    const router = useRouter()
    const project = ref(null)
    const loading = ref(true)
    const isFollowed = ref(false)
    const showPopup = ref(false)
    const showProgressPopup = ref(false)
    const tableData = ref([
      {
        header1: '立项',
        value1: '无需办理',
        handling_level: '',
        handling_time: '',
        paper_situation: ''
      }
    ])

    // 折叠状态管理
    const collapseState = reactive({
      basicInfo: true,
      investInfo: false,
      timeInfo: false,
      responsibilityInfo: false
    })

    const toggleCollapse = (section) => {
      collapseState[section] = !collapseState[section]
    }

    const toggleFollow = () => {
      isFollowed.value = !isFollowed.value
      alert(isFollowed.value ? '已关注项目' : '已取消关注')
    }

    const getStatusClass = (value) => {
      return {
        'status-yes': value === '是',
        'status-no': value === '否',
        'status-not-required': value === '无需办理'
      }
    }

    const truncateText = (text, maxLength) => {
      if (text && text.length > maxLength) {
        return text.substring(0, maxLength) + '...'
      }
      return text
    }

    const openPopup = () => {
      showPopup.value = true
      // 在实际应用中，这里应该调用API获取审批手续数据
      // 目前使用模拟数据
      tableData.value = [
        { header1: '立项', value1: '无需办理' },
        { header1: '建设工程文物保护和考古许可', value1: '是' },
        { header1: '用地预审和规划选址意见书', value1: '否' },
        { header1: '新增建设用地审批', value1: '无需办理' },
        { header1: '建设用地规划许可审批', value1: '是' }
      ]
    }

    const closePopup = () => {
      showPopup.value = false
    }

    const openPopupProgress = () => {
      showProgressPopup.value = true
    }

    const closePopupProgress = () => {
      showProgressPopup.value = false
    }

    const goDetail = (status, index) => {
      if (status === false) {
        router.push('/project-status-false/' + project.value.id)
      } else {
        router.push('/project-status-true/' + project.value.id)
      }
    }

    // 获取项目详情
    const getProjectDetail = async () => {
      const projectId = route.params.id
      if (!projectId) {
        loading.value = false
        return
      }

      try {
        // 尝试从API获取数据
        const response = await axios.get(config.getUrl('project_detail'), {
          params: { id: projectId }
        })
        
        if (response.data && response.data.result) {
          project.value = {
            id: response.data.result.id,
            name: response.data.result.xmmc,
            investor: response.data.result.tzzt,
            progress: response.data.result.xmjd || 0,
            address: response.data.result.xmdz,
            investment: response.data.result.tzje,
            period: response.data.result.jszq,
            // 新增字段
            level: response.data.result.ddcj || '市级重点项目',
            nature: response.data.result.jsxz || '新建',
            totalInvestment: response.data.result.ztz || response.data.result.tzje,
            plannedInvestment2025: response.data.result.jhwc || '暂无数据',
            plannedStartDate: response.data.result.fgsj || '暂无数据',
            plannedEndDate: response.data.result.wgsj || '暂无数据',
            supervisor: response.data.result.fgld || '暂无数据',
            responsibleUnit: response.data.result.fzdw || '暂无数据',
            progressDetails: response.data.result.xmjzqk || '暂无项目进展数据',
            images: [],
            timeline: []
          }
        }
      } catch (error) {
        console.error('获取项目详情失败:', error)
        
        // 使用模拟数据
        const mockProjects = [
          {
            id: 1,
            name: '智慧城市建设项目',
            investor: '城市发展投资有限公司',
            progress: 100,
            address: '巴林右旗城区',
            investment: '1亿元',
            period: '2023年-2024年',
            level: '市级重点项目',
            nature: '新建',
            totalInvestment: '50000',
            plannedInvestment2025: '20000',
            plannedStartDate: '2025-03-01',
            plannedEndDate: '2025-12-31',
            supervisor: '张三',
            responsibleUnit: '城市建设局',
            progressDetails: '智慧城市建设项目已于2023年12月30日全部完工并投入使用。该项目包括智慧交通、智慧安防、智慧政务等多个子系统，目前各系统运行良好，为市民提供了便捷的城市服务。',
            images: ['project1-1.svg', 'project1-2.svg'],
            timeline: [
              { date: '2023-01-15', title: '项目立项', description: '项目正式获得批准立项' },
              { date: '2023-03-20', title: '开工建设', description: '项目正式开始建设' },
              { date: '2023-08-10', title: '完成主体工程', description: '主体工程已完工' },
              { date: '2023-12-30', title: '项目竣工', description: '项目全部完工并投入使用' }
            ]
          },
          {
            id: 2,
            name: '绿色能源产业园',
            investor: '新能源科技集团',
            progress: 45,
            address: '巴林右旗工业园区',
            investment: '8000万元',
            period: '2023年-2025年',
            level: '市级重点项目',
            nature: '新建',
            totalInvestment: '8000',
            plannedInvestment2025: '3000',
            plannedStartDate: '2023-02-25',
            plannedEndDate: '2025-12-31',
            supervisor: '李四',
            responsibleUnit: '工业和信息化局',
            progressDetails: '绿色能源产业园项目于2023年5月10日正式开工建设，目前已完成一期工程，包括光伏发电站和风力发电站的基础设施建设。二期工程计划于2024年3月开始，将建设能源储存设施和智能电网系统。',
            images: ['project2-1.svg', 'project2-2.svg'],
            timeline: [
              { date: '2023-02-25', title: '项目立项', description: '项目正式获得批准立项' },
              { date: '2023-05-10', title: '开工建设', description: '项目正式开始建设' },
              { date: '2023-11-20', title: '完成一期工程', description: '一期工程已完工' }
            ]
          },
          {
            id: 3,
            name: '智能制造产业基地',
            investor: '工业发展有限公司',
            progress: 30,
            address: '巴林右旗经济开发区',
            investment: '1.2亿元',
            period: '2023年-2026年',
            level: '市级重点项目',
            nature: '新建',
            totalInvestment: '120000',
            plannedInvestment2025: '50000',
            plannedStartDate: '2023-03-15',
            plannedEndDate: '2026-06-30',
            supervisor: '王五',
            responsibleUnit: '发展和改革委员会',
            progressDetails: '智能制造产业基地项目于2023年6月20日正式开工建设，目前已完成土地平整和基础设施建设，厂房主体结构正在施工中。预计2024年底完成一期工程，2025年开始招商引资。',
            images: ['project3-1.svg', 'project3-2.svg'],
            timeline: [
              { date: '2023-03-15', title: '项目立项', description: '项目正式获得批准立项' },
              { date: '2023-06-20', title: '开工建设', description: '项目正式开始建设' }
            ]
          },
          {
            id: 4,
            name: '文化创意产业园',
            investor: '文化传媒投资集团',
            progress: 90,
            address: '巴林右旗文化新区',
            investment: '6000万元',
            period: '2023年-2024年',
            level: '市级重点项目',
            nature: '新建',
            totalInvestment: '6000',
            plannedInvestment2025: '1000',
            plannedStartDate: '2023-01-10',
            plannedEndDate: '2024-12-31',
            supervisor: '赵六',
            responsibleUnit: '文化和旅游局',
            progressDetails: '文化创意产业园项目已完成主体工程建设，目前正在进行内部装修和设备安装。已有多家文创企业签约入驻，预计2024年3月正式开园运营。',
            images: ['project4-1.svg', 'project4-2.svg'],
            timeline: [
              { date: '2023-01-10', title: '项目立项', description: '项目正式获得批准立项' },
              { date: '2023-03-05', title: '开工建设', description: '项目正式开始建设' },
              { date: '2023-07-15', title: '完成主体工程', description: '主体工程已完工' },
              { date: '2023-11-10', title: '内部装修', description: '内部装修工作进行中' }
            ]
          }
        ]
        
        // 查找匹配的项目
        const foundProject = mockProjects.find(p => p.id === parseInt(projectId));
        console.log('Project ID:', projectId, 'Found project:', foundProject);
        
        project.value = foundProject || {
          id: projectId,
          name: '项目详情页面正在开发中',
          investor: '暂无数据',
          progress: 0,
          address: '暂无数据',
          investment: '暂无数据',
          period: '暂无数据',
          level: '暂无数据',
          nature: '暂无数据',
          totalInvestment: '暂无数据',
          plannedInvestment2025: '暂无数据',
          plannedStartDate: '暂无数据',
          plannedEndDate: '暂无数据',
          supervisor: '暂无数据',
          responsibleUnit: '暂无数据',
          progressDetails: '暂无项目进展数据',
          images: [],
          timeline: []
        }
      } finally {
        loading.value = false
      }
    }

    // 获取图片URL
    const getImageUrl = (image) => {
      if (!image) return '/src/assets/images/projects/default-project.svg'
      try {
        return `/src/assets/images/projects/${image}`
      } catch (e) {
        return '/src/assets/images/projects/default-project.svg'
      }
    }

    onMounted(() => {
      getProjectDetail()
    })

    return {
      project,
      loading,
      isFollowed,
      showPopup,
      showProgressPopup,
      tableData,
      collapseState,
      toggleCollapse,
      toggleFollow,
      getStatusClass,
      truncateText,
      openPopup,
      closePopup,
      openPopupProgress,
      closePopupProgress,
      goDetail,
      getImageUrl
    }
  }
}
</script>

<style scoped lang="scss">
// 全局变量
$primary-color: #1890FF;
$success-color: #52C41A;
$warning-color: #FAAD14;
$danger-color: #F5222D;
$background-color: #F5F7FA;
$card-color: #FFFFFF;
$text-primary: #333333;
$text-secondary: #666666;
$text-tertiary: #999999;
$border-radius: 8px;
$shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
$transition: all 0.3s ease;

.project-detail-container {
  min-height: 100vh;
  background: $background-color;
  padding: 30px;
  max-width: 1200px;
  margin: 0 auto;

  .loading,
  .error {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 300px;
    font-size: 18px;
    color: $text-tertiary;
  }

  .project-detail {
    .project-header {
      background: $card-color;
      border-radius: $border-radius;
      padding: 20px;
      margin-bottom: 20px;
      box-shadow: $shadow;
      display: flex;
      justify-content: space-between;
      align-items: center;
      flex-wrap: wrap;

      .project-title {
        font-size: 24px;
        color: $text-primary;
        margin: 0;
        flex: 1;
        min-width: 300px;
      }

      .project-progress {
        display: flex;
        align-items: center;
        min-width: 300px;
        margin-top: 10px;

        .progress-label {
          font-size: 14px;
          color: $text-secondary;
          margin-right: 10px;
        }

        .progress-bar {
          flex: 1;
          height: 10px;
          background: #E9ECEF;
          border-radius: 5px;
          overflow: hidden;
          margin: 0 10px;

          .progress-fill {
            height: 100%;
            background: linear-gradient(to right, $primary-color, #87CEFA);
            border-radius: 5px;
          }
        }

        .progress-value {
          font-size: 14px;
          color: $primary-color;
          font-weight: 600;
        }
      }
    }

    // 项目图片卡片
    .project-image-card {
      background: $card-color;
      border-radius: $border-radius;
      margin-bottom: 20px;
      box-shadow: $shadow;
      overflow: hidden;
      position: relative;
      height: 250px;

      .project-image {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }

      .follow-button {
        position: absolute;
        bottom: 20px;
        right: 20px;
        background: rgba(255, 255, 255, 0.9);
        border-radius: 20px;
        padding: 8px 16px;
        cursor: pointer;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
        transition: $transition;

        span {
          font-size: 14px;
          color: $primary-color;
          font-weight: 600;
        }

        &:hover {
          transform: scale(1.05);
        }
      }
    }

    // 卡片通用样式
    .card {
      background: $card-color;
      border-radius: $border-radius;
      margin-bottom: 20px;
      box-shadow: $shadow;
      overflow: hidden;

      &.action-card {
        cursor: pointer;
        transition: $transition;

        &:hover {
          transform: translateY(-2px);
          box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
        }
      }

      .card-header {
        padding: 15px 20px;
        border-bottom: 1px solid #E9ECEF;
        display: flex;
        justify-content: space-between;
        align-items: center;
        cursor: pointer;

        .card-title {
          font-size: 18px;
          color: $text-primary;
          margin: 0;
        }

        .card-arrow {
          font-size: 20px;
          color: $text-tertiary;
          transform: rotate(90deg);
          transition: $transition;

          &.is-open {
            transform: rotate(270deg);
          }
        }

        .card-action {
          font-size: 14px;
          color: $primary-color;
        }
      }

      .card-content {
        padding: 20px;

        .info-list {
          .info-item {
            display: flex;
            margin-bottom: 15px;
            align-items: flex-start;

            &:last-child {
              margin-bottom: 0;
            }

            .info-label {
              width: 150px;
              color: $text-secondary;
              font-size: 14px;
            }

            .info-value {
              flex: 1;
              color: $text-primary;
              font-size: 14px;
            }
          }
        }

        .image-gallery {
          display: grid;
          grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
          gap: 15px;

          .gallery-item {
            border-radius: $border-radius;
            overflow: hidden;
            box-shadow: $shadow;

            img {
              width: 100%;
              height: 200px;
              object-fit: cover;
              transition: transform 0.3s ease;

              &:hover {
                transform: scale(1.05);
              }
            }
          }
        }
      }
    }

    // 弹窗样式
    .popup-wrapper {
      position: fixed;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      display: flex;
      align-items: center;
      justify-content: center;
      z-index: 1000;

      .popup-overlay {
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: rgba(0, 0, 0, 0.5);
      }

      .popup-content {
        position: relative;
        width: 90%;
        max-width: 600px;
        max-height: 80vh;
        background: $card-color;
        border-radius: $border-radius;
        box-shadow: 0 4px 16px rgba(0, 0, 0, 0.2);
        overflow: hidden;
        display: flex;
        flex-direction: column;
        z-index: 1001;

        .popup-header {
          padding: 20px;
          border-bottom: 1px solid #E9ECEF;

          .popup-title {
            font-size: 20px;
            color: $text-primary;
            margin: 0;
          }
        }

        .popup-body {
          padding: 20px;
          overflow-y: auto;
          flex: 1;

          .table-content {
            .table-row {
              margin-bottom: 15px;
              padding-bottom: 15px;
              border-bottom: 1px solid #E9ECEF;

              &:last-child {
                margin-bottom: 0;
                padding-bottom: 0;
                border-bottom: none;
              }

              .table-cell {
                .cell-label {
                  display: block;
                  font-size: 16px;
                  color: $text-primary;
                  margin-bottom: 10px;
                  font-weight: 500;
                }

                .cell-value-container {
                  display: flex;
                  align-items: center;
                  justify-content: space-between;

                  .cell-value {
                    padding: 6px 12px;
                    border-radius: 4px;
                    font-size: 14px;

                    &.status-yes {
                      background: rgba($success-color, 0.1);
                      color: $success-color;
                    }

                    &.status-no {
                      background: rgba($danger-color, 0.1);
                      color: $danger-color;
                    }

                    &.status-not-required {
                      background: rgba($warning-color, 0.1);
                      color: $warning-color;
                    }
                  }

                  .detail-link {
                    color: $primary-color;
                    font-size: 14px;
                    cursor: pointer;

                    &:hover {
                      text-decoration: underline;
                    }
                  }
                }
              }
            }
          }

          .progress-content {
            .progress-text {
              font-size: 16px;
              color: $text-primary;
              line-height: 1.6;
            }
          }
        }

        .popup-close {
          position: absolute;
          top: 15px;
          right: 15px;
          width: 30px;
          height: 30px;
          display: flex;
          align-items: center;
          justify-content: center;
          cursor: pointer;
          z-index: 1002;

          .close-icon {
            font-size: 24px;
            color: $text-tertiary;
            transition: $transition;
          }

          &:hover .close-icon {
            color: $text-primary;
          }
        }
      }
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .project-detail-container {
    padding: 15px;

    .project-detail {
      .project-header {
        flex-direction: column;
        align-items: flex-start;

        .project-title {
          margin-bottom: 15px;
        }

        .project-progress {
          width: 100%;
        }
      }

      .card {
        .card-content {
          .info-list {
            .info-item {
              flex-direction: column;

              .info-label {
                width: 100%;
                margin-bottom: 5px;
              }
            }
          }

          .image-gallery {
            grid-template-columns: 1fr;
          }
        }
      }

      .popup-wrapper {
        .popup-content {
          width: 95%;
          max-height: 90vh;
        }
      }
    }
  }
}
</style>
